package com.vanlian.client.logic;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vanlian.client.config.Constance;
import com.vanlian.client.until.PayResult;
import com.vanlian.client.until.PostUtils;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanggenlin on 17-6-14.
 */
public class PayController {


    static  PayController instance;

    public static PayController getInstance() {
        if (instance ==null){
            instance = new PayController();
        }
        return instance;
    }


    /**
     *
     * @param vlPayNo
     * @param orderId
     *  payChannel  app_alipay
     * @param title
     * @param price
     */

    public void wechatPay(String vlPayNo,String orderId,String title,String price,Activity activity){

        try {

            List<NameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("orderId",orderId));
            list.add(new BasicNameValuePair("pay_channel","app_weixin"));
            list.add(new BasicNameValuePair("title",title));
            list.add(new BasicNameValuePair("price",price));
            list.add(new BasicNameValuePair("vl_pay_no",vlPayNo));
            new PayThread(list,true,activity).execute();
        }catch (Exception e){

        }


    }

    /**
     *
     * @param lisener
     * @param vlPayNo
     * @param orderId
     * payChannel  app_weixin  app_alipay
     * @param title
     * @param price
     * @param context
     */
    public void aliPay(final PayBackLisener lisener, String vlPayNo, String orderId, String title, String price, final Activity context){

        try {
            EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);

            List<NameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("orderId",orderId));
            list.add(new BasicNameValuePair("pay_channel","app_alipay"));
            list.add(new BasicNameValuePair("title",title));
            list.add(new BasicNameValuePair("price",price));
            list.add(new BasicNameValuePair("vl_pay_no",vlPayNo));
            new PayThread(list,false,context,lisener).execute();
        }catch (Exception E){
        }
    }

    private  class AliHandler extends Handler{
        PayBackLisener lisener;

        public AliHandler(PayBackLisener lisener) {
            this.lisener = lisener;
        }
        @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1: {
                        PayResult payResult = new PayResult((String) msg.obj);
                        String resultStatus = payResult.getResultStatus();
                        if (TextUtils.equals(resultStatus, "9000")) {
                            lisener.onPaySuccess();
                        } else {
                            lisener.onPayFail();
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
    }



    public interface PayBackLisener {
        void onPaySuccess();
        void onPayFail();
    }


    public class PayThread extends AsyncTask{
        List<NameValuePair> list;
        Activity context;
        PayBackLisener lisener;
        public PayThread(List<NameValuePair> list,boolean isWechat, Activity context,PayBackLisener lisener) {
            this.list = list;
            this.context = context;
            this.lisener = lisener;
            this.isWechat = isWechat;
        }

        boolean isWechat;
        public PayThread(List<NameValuePair> list,boolean isWechat,Activity activity) {
            this.list = list;
            this.isWechat = isWechat;
            this.context  =activity;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] params) {
            String repones = PostUtils.httpPost(Constance.payUrl,list);
            Log.e("respones",repones);
            if (!isWechat){
                PayTask alipay = new PayTask(context);
                try {
                    JSONObject jsonObject  = new JSONObject(repones);
                    String payInfor = jsonObject.getString("payInfo");
                    Log.e("payInfor ",payInfor);
                    String result = alipay.pay(payInfor,true);
                    Log.e("result ",result);
                    return result;
                }catch (Exception e){
                }
            }else{
                try {
                    JSONObject jsonObject  = new JSONObject(repones);
                    JSONObject payInfor = jsonObject.getJSONObject("payInfo");
                    return payInfor;
                }catch (Exception e){
                }
            }

            return "";
        }


        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            if (!isWechat){
                Log.e("respones11 ",o.toString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = o.toString();
                new AliHandler(lisener).sendMessage(msg);
            }else{

                try {
                    JSONObject json = (JSONObject)o;
                    PayReq req = new PayReq();
                    req.appId			= json.getString("appid");
                    req.partnerId		= json.getString("partnerid");
                    req.prepayId		= json.getString("prepayid");
                    req.nonceStr		= json.getString("noncestr");
                    req.timeStamp		= json.getString("timestamp");
                    req.packageValue	= json.getString("package");
                    req.sign			= json.getString("sign");


//                    req.appId			= "wxb7837544e8e4b6a6";
//                    req.partnerId		= "1461973802";
//
//                    req.prepayId		= "wx20170614195841c8a64e038d0222380981";
//                    req.nonceStr		= "iktgc38tuvh76hzphhqp16lxko86gohg";
//                    req.timeStamp		= (int)System.currentTimeMillis()/1000+"";
//                    req.packageValue	= "Sign=WXPay";
//                    req.sign			= "A7F33D78D1DE277B04B9FEA3BF9E9DDF";
                    // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                    Log.e("json==",json.toString());
                    IWXAPI api = WXAPIFactory.createWXAPI(context,null);
                    api.registerApp(Constance.wechatAppId);
                    api.sendReq(req);
                }catch (Exception e){

                }

            }

        }
    }
}
